<template>
    <div class="detail-container">
        <NavBar>
            <template #default>
                详情
            </template>
        </NavBar>
        <div class="product-detail">
            <!-- 商品图片 -->
            <div class="product-image">
                <img :src="item.mainImage" alt="商品图片">
            </div>

            <!-- 商品信息 -->
            <div class="product-info">
                <h2 class="product-name">{{ item.productName }}</h2>
                <p class="product-price">¥{{ item.price }}</p>
                <p class="product-desc">{{ item.detail }}</p>
            </div>

            <!-- 商品评价 -->
            <div class="product-reviews">
                <ReviewsView :showPopup="showPopup" @update:showPopup="showPopup = $event" />

                <div class="review-list">
                    <div class="review-item">
                        <div class="user-info">
                            <img src="https://via.placeholder.com/40" class="avatar">
                            <span class="username">用户1234</span>
                        </div>
                        <div class="review-content">
                            <div class="rating">
                                <el-icon>
                                    <StarFilled />
                                </el-icon>
                                <el-icon>
                                    <StarFilled />
                                </el-icon>
                                <el-icon>
                                    <StarFilled />
                                </el-icon>
                                <el-icon>
                                    <StarFilled />
                                </el-icon>
                                <el-icon>
                                    <Star />
                                </el-icon>
                                <span class="rating-text">4.0</span>
                            </div>
                            <p class="review-text">质量很好，穿着很舒服，下次还会购买</p>
                            <div class="review-images">
                                <img src="https://via.placeholder.com/80" alt="评价图片">
                                <img src="https://via.placeholder.com/80" alt="评价图片">
                            </div>
                            <p class="review-time">2023-05-15</p>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 商品详情图片 -->
            <div class="product-detail-images">
                <div class="section-title">
                    <h3>商品详情</h3>
                </div>
                <img :src="item.url" alt="商品图片">
            </div>
        </div>

        <!-- 底部操作栏 -->
        <div class="action-bar">
            <div class="action-icons">
                <div class="action-item">
                    <el-icon>
                        <ChatDotRound />
                    </el-icon>
                    <span>客服</span>
                </div>
                <router-link to="/shopcart" class="cart-link">
                    <div class="action-item">
                        <el-icon>
                            <ShoppingCart />
                        </el-icon>
                        <span>购物车</span>
                        <span class="cart-count" v-if="cartStore.totalItems > 0">
                            {{ cartStore.totalItems }}
                        </span>
                    </div>
                </router-link>
            </div>
            <div class="action-buttons">
                <button
                    class="add-cart"
                    @click="addCart"
                    :disabled="isAddingToCart"
                >
                    <span v-if="!isAddingToCart">加入购物车</span>
                    <span v-else>添加中...</span>
                </button>
                <button class="buy-now" @click="openBuyDialog">立即购买</button>
            </div>
        </div>

        <!-- 立即购买弹窗 -->
        <el-dialog
            v-model="dialogVisible"
            title="立即购买"
            width="90%"
            top="5vh"
            :close-on-click-modal="false"
        >
            <div class="buy-dialog-container">
                <!-- 商品信息 -->
                <div class="product-info">
                    <img :src="item.mainImage" class="product-image">
                    <div class="product-details">
                        <h4>{{ item.productName }}</h4>
                        <p class="price">¥{{ item.price }}</p>
                    </div>
                </div>

                <!-- 购买数量 -->
                <div class="quantity-section">
                    <span>购买数量</span>
                    <el-input-number
                        v-model="buyQuantity"
                        :min="1"
                        :max="99"
                        size="small"
                    />
                </div>

                <!-- 地址选择部分 -->
                <div class="address-section" @click="showAddressList = true">
                    <div class="address-header">
                        <span class="title">收货地址</span>
                        <el-icon><ArrowRight /></el-icon>
                    </div>
                    <div v-if="selectedAddress" class="address-content">
                        <div class="address-info">
                            <span class="receiver">{{ selectedAddress.receiverName }}</span>
                            <span class="phone">{{ selectedAddress.receiverMobile }}</span>
                            <el-tag v-if="selectedAddress.isDefault" size="small" type="danger">默认</el-tag>
                        </div>
                        <div class="address-detail">
                            {{ selectedAddress.province }}{{ selectedAddress.city }}{{ selectedAddress.district }}{{ selectedAddress.detailAddress }}
                        </div>
                    </div>
                    <div v-else class="address-empty">
                        <el-text type="danger">请选择收货地址</el-text>
                    </div>
                </div>

                <!-- 支付方式部分 -->
                <div class="payment-section">
                    <div class="payment-header">选择支付方式</div>
                    <div class="payment-methods">
                        <div
                            class="payment-method"
                            :class="{ 'active': paymentType === 1 }"
                            @click="paymentType = 1"
                        >
                            <div class="method-icon">
                                <img src="@/assets/alipay.png" alt="支付宝">
                            </div>
                            <div class="method-name">支付宝</div>
                        </div>
                    </div>
                </div>
            </div>

            <template #footer>
                <div class="payment-footer">
                    <div class="payment-amount">
                        应付：<span class="amount">¥{{ (item.price * buyQuantity).toFixed(2) }}</span>
                    </div>
                    <div class="payment-actions">
                        <el-button plain @click="dialogVisible = false">取消</el-button>
                        <el-button
                            type="primary"
                            :loading="isProcessing"
                            @click="handleBuyNow"
                            :disabled="!selectedAddress || paymentType === 0 || isProcessing"
                        >
                            立即支付
                        </el-button>
                    </div>
                </div>
            </template>
        </el-dialog>

        <!-- 地址选择抽屉 -->
        <el-drawer
            v-model="showAddressList"
            title="选择收货地址"
            direction="btt"
            size="60%"
        >
            <div class="address-list-container">
                <div
                    v-for="address in addressList"
                    :key="address.addressId"
                    class="address-item"
                    :class="{ 'active': selectedAddress?.addressId === address.addressId }"
                    @click="selectAddress(address)"
                >
                    <div class="address-content">
                        <div class="address-header">
                            <span class="receiver">{{ address.receiverName }}</span>
                            <span class="phone">{{ address.receiverMobile }}</span>
                            <el-tag v-if="address.isDefault" size="small" type="danger">默认</el-tag>
                        </div>
                        <div class="address-detail">
                            {{ address.province }}{{ address.city }}{{ address.district }}{{ address.detailAddress }}
                        </div>
                    </div>
                    <el-icon class="check-icon" v-if="selectedAddress?.addressId === address.addressId">
                        <Check />
                    </el-icon>
                </div>

                <div class="address-actions">
                    <el-button type="primary" @click="showAddressList = false">确认选择</el-button>
                </div>
            </div>
        </el-drawer>

        <!-- 支付二维码弹窗 -->
        <el-dialog
            v-model="showPaymentDialog"
            title="请使用支付宝扫码支付"
            width="300px"
            :close-on-click-modal="false"
        >
            <div class="qr-code-container">
                <canvas ref="qrCodeCanvas" class="qr-code-canvas"></canvas>
                <div class="qr-code-info">
                    <p>订单号: {{ currentOrderId }}</p>
                    <p>金额: ¥{{ currentAmount }}</p>
                    <p v-if="isSandbox" class="sandbox-tip">(沙箱测试环境)</p>
                </div>
                <div class="payment-instruction">
                    <p>请使用支付宝APP扫码支付</p>
                    <p v-if="isSandbox">使用支付宝沙箱账号支付</p>
                </div>
            </div>
            <template #footer>
                <el-button type="primary" @click="handlePaymentComplete">已完成支付</el-button>
                <el-button @click="refreshQrCode" :loading="refreshingQrCode">刷新二维码</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import NavBar from '../../components/common/NavBar.vue';
import { useRoute, useRouter } from 'vue-router';
import { ChatDotRound, ShoppingCart, Star, StarFilled, ArrowRight, Check } from '@element-plus/icons-vue';
import ReviewsView from './ReviewsView.vue';
import { ref, computed, onMounted, onBeforeUnmount, nextTick } from 'vue';
import { useCartStore } from '@/stores/cartStore';
import { useAddressStore } from '@/stores/addressStore';
import { useOrderStore } from '@/stores/orderStore';
import { useUserStore } from '@/stores/userStore';
import { ElMessage } from 'element-plus';
import QRCode from 'qrcode';
// import axios from 'axios';
import { getPaymentQRCode, checkPaymentStatus } from '@/api/Payment';

const route = useRoute();
const router = useRouter();
const item = ref(JSON.parse(route.query.item));
const showPopup = ref(false);
const isAddingToCart = ref(false);
const cartStore = useCartStore();
const addressStore = useAddressStore();
const orderStore = useOrderStore();
const userStore = useUserStore();

// 立即购买相关状态
const dialogVisible = ref(false);
const buyQuantity = ref(1);
const paymentType = ref(1); // 1-支付宝
const isProcessing = ref(false);
const showAddressList = ref(false);
const selectedAddress = ref(null);
const showPaymentDialog = ref(false);
const currentOrderId = ref('');
const currentAmount = ref(0);
const qrCodeCanvas = ref(null);
const isSandbox = ref(false);
const refreshingQrCode = ref(false);
const paymentStatusPolling = ref(null);

const addressList = computed(() => addressStore.addressList);

/**
 * 添加商品到购物车
 */
const addCart = async () => {
    try {
        isAddingToCart.value = true;
        await cartStore.addToCart(item.value);
        ElMessage.success('已添加到购物车');
    } catch (error) {
        console.error('添加购物车失败:', error);
        ElMessage.error('添加购物车失败');
    } finally {
        isAddingToCart.value = false;
    }
};

/**
 * 显示立即购买弹窗
 */
const openBuyDialog = () => {
    if (!userStore.isLogin) {
        ElMessage.warning('请先登录');
        router.push('/login');
        return;
    }
    dialogVisible.value = true;
    buyQuantity.value = 1;
};

/**
 * 选择地址
 */
const selectAddress = (address) => {
    selectedAddress.value = address;
};

/**
 * 生成二维码
 */
const generateQrCode = (url) => {
    if (!qrCodeCanvas.value) return;

    QRCode.toCanvas(qrCodeCanvas.value, url, {
        width: 200,
        margin: 1,
        color: {
            dark: '#000000',
            light: '#ffffff'
        }
    }, (error) => {
        if (error) {
            console.error('生成二维码失败:', error);
            ElMessage.error('生成支付二维码失败');
        }
    });
};

/**
 * 刷新二维码
 */
const refreshQrCode = async () => {
    try {
        refreshingQrCode.value = true;
        const response = await getPaymentQRCode({
            ordersId: currentOrderId.value,
            totalAmount: currentAmount.value,
            subject: `订单支付 - ${item.value.productName}`
        });
        // const response = await axios.get('https://2b15fa7cb754.ngrok-free.app/product/api/payment/qr-code', {
        //     params: {
        //         ordersId: currentOrderId.value,
        //         totalAmount: currentAmount.value,
        //         subject: `订单支付 - ${item.value.productName}`
        //     },
        //     headers: {
        //         'ngrok-skip-browser-warning': 'true'
        //     }
        // });

        if (response.data.code === 1) {
            generateQrCode(response.data.data.qrCodeUrl);
            ElMessage.success('二维码已刷新');
        }
    } catch (error) {
        ElMessage.error('刷新二维码失败');
    } finally {
        refreshingQrCode.value = false;
    }
};

/**
 * 开始轮询支付状态
 */
const startPaymentPolling = (orderId) => {
    if (paymentStatusPolling.value) {
        clearInterval(paymentStatusPolling.value);
    }

    paymentStatusPolling.value = setInterval(async () => {
        try {
            const response = await checkPaymentStatus(orderId);
            // const response = await axios.get(
            //     `https://2b15fa7cb754.ngrok-free.app/product/api/payment/status?orderId=${orderId}`, {
            //         headers: {
            //             'ngrok-skip-browser-warning': 'true'
            //         }
            //     }
            // );

            if (response.data.code === 1 && response.data.data?.paid) {
                clearInterval(paymentStatusPolling.value);
                showPaymentDialog.value = false;
                ElMessage.success('支付成功！');
                router.push('/order/detail/' + orderId);
            }
        } catch (error) {
            console.error('支付状态查询失败:', error);
        }
    }, 3000);

    setTimeout(() => {
        if (paymentStatusPolling.value) {
            clearInterval(paymentStatusPolling.value);
            ElMessage.warning('支付状态查询超时，请检查支付是否完成');
        }
    }, 300000);
};

/**
 * 处理立即购买
 */
const handleBuyNow = async () => {
    if (!selectedAddress.value) {
        ElMessage.warning('请选择收货地址');
        return;
    }

    try {
        isProcessing.value = true;

        const orderData = {
            userId: userStore.userAccount.userId,
            addressId: selectedAddress.value.addressId,
            items: [{
                productId: item.value.productId,
                quantity: buyQuantity.value,
                price: item.value.price
            }]
        };

        const createOrderResponse = await orderStore.createOrder(orderData);

        if (createOrderResponse.code !== 1) {
            throw new Error(createOrderResponse.msg || '订单创建失败');
        }

        const outTradeNo = createOrderResponse.data.orderId;
        currentOrderId.value = outTradeNo;
        currentAmount.value = (item.value.price * buyQuantity.value).toFixed(2);

        const qrCodeResponse = await getPaymentQRCode({
            ordersId: outTradeNo,
            totalAmount: currentAmount.value,
            subject: `订单支付 - ${item.value.productName}`,
        });

        // const qrCodeResponse = await axios.get('https://2b15fa7cb754.ngrok-free.app/product/api/payment/qr-code', {
        //     params: {
        //         ordersId: outTradeNo,
        //         totalAmount: currentAmount.value,
        //         subject: `订单支付 - ${item.value.productName}`,
        //         body: `购买${item.value.productName} ${buyQuantity.value}件`
        //     },
        //     headers: {
        //         'ngrok-skip-browser-warning': 'true'
        //     }
        // });

        if (qrCodeResponse.data.code === 1) {
            isSandbox.value = qrCodeResponse.data.data.isSandbox || false;
            showPaymentDialog.value = true;
            dialogVisible.value = false;

            nextTick(() => {
                generateQrCode(qrCodeResponse.data.data.qrCodeUrl);
            });

            startPaymentPolling(outTradeNo);
        } else {
            throw new Error(qrCodeResponse.data.msg || '获取支付二维码失败');
        }
    } catch (error) {
        console.error('支付错误:', error);
        ElMessage.error(error.response?.data?.msg || error.message || '支付失败');
    } finally {
        isProcessing.value = false;
    }
};

/**
 * 处理支付完成
 */
const handlePaymentComplete = () => {
    showPaymentDialog.value = false;
    ElMessage.success('支付已完成');
    router.push('/order/detail/' + currentOrderId.value);
};

// 初始化地址数据
onMounted(async () => {
    if (userStore.isLogin) {
        await addressStore.initAddresses();
        const defaultAddress = addressList.value.find(item => item.isDefault === 1);
        if (defaultAddress) {
            selectedAddress.value = defaultAddress;
        }
    }
});

onBeforeUnmount(() => {
    if (paymentStatusPolling.value) {
        clearInterval(paymentStatusPolling.value);
    }
});
</script>

<style scoped>
.detail-container {
    background-color: #f7f5f5;
    padding-bottom: 70px; /* Add padding to prevent content from being hidden behind fixed action bar */
}

.product-detail {
    padding: 0 10px;
}

.product-image img {
    width: 100%;
    height: auto;
    display: block;
    background-color: #fff;
}

.product-info {
    padding: 15px;
    background-color: #fff;
    margin-bottom: 10px;
    border-radius: 10px;
    border: 1px solid #f0eeee;
}

.product-name {
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 10px;
    line-height: 1.4;
}

.product-price {
    color: #ff5000;
    font-size: 22px;
    font-weight: bold;
    margin: 10px 0;
}

.product-desc {
    color: #666;
    font-size: 14px;
    line-height: 1.6;
}

/* 评价区域样式 */
.product-reviews {
    background-color: #fff;
    padding: 15px;
    margin-bottom: 10px;
    border-radius: 10px;
    border: 1px solid #f0f0f0;
}

.section-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
}

.section-title h3 {
    font-size: 16px;
    font-weight: bold;
    margin-left: 10px;
}

.more {
    color: #999;
    font-size: 12px;
}

.review-item {
    padding: 15px 0;
    border-bottom: 1px solid #f0f0f0;
}

.user-info {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
}

.avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    margin-right: 10px;
}

.username {
    font-size: 14px;
    color: #333;
}

.rating {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
}

.rating .el-icon {
    color: #ff9900;
    font-size: 16px;
    margin-right: 3px;
}

.rating-text {
    color: #ff9900;
    font-size: 14px;
    margin-left: 5px;
}

.review-text {
    font-size: 14px;
    color: #333;
    line-height: 1.6;
    margin-bottom: 10px;
}

.review-images {
    display: flex;
    gap: 10px;
    margin-bottom: 10px;
}

.review-images img {
    width: 80px;
    height: 80px;
    border-radius: 4px;
    object-fit: cover;
}

.review-time {
    font-size: 12px;
    color: #999;
}

/* 商品详情图片 */
.product-detail-images {
    background-color: #fff;
    padding: 15px 0;
    border-radius: 10px;
    border: 1px solid #f0f0f0;
}

.product-detail-images img {
    width: 100%;
    display: block;
    margin-bottom: -1px; /* 消除图片间缝隙 */
}

/* 底部操作栏样式 */
.action-bar {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    height: 65px;
    background: #fff;
    display: flex;
    align-items: center;
    box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
    z-index: 1000;
    padding: 0 10px;
}

.action-icons {
    display: flex;
    flex: 1;
}

.cart-link {
    text-decoration: none;
    color: inherit;
}

.action-item {
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 60px;
    font-size: 12px;
    color: #666;
}

.action-item .el-icon {
    font-size: 20px;
    margin-bottom: 2px;
}

.cart-count {
    position: absolute;
    top: -5px;
    right: 5px;
    background-color: #ff5000;
    color: white;
    border-radius: 50%;
    width: 18px;
    height: 18px;
    font-size: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.action-buttons {
    display: flex;
    flex: 2;
}

.add-cart,
.buy-now {
    flex: 1;
    height: 40px;
    border: none;
    border-radius: 20px;
    color: white;
    font-size: 14px;
    font-weight: bold;
    margin-left: 10px;
    cursor: pointer;
}

.add-cart {
    background: linear-gradient(to right, #ffd01e, #ff8f00);
}

.add-cart:disabled {
    opacity: 0.7;
    cursor: not-allowed;
}

.buy-now {
    background: linear-gradient(to right, #ff6034, #ff1d00);
}

/* 购买弹窗样式 */
.buy-dialog-container {
    padding: 0 10px;
}

.product-info {
    display: flex;
    margin-bottom: 20px;
}

.product-info .product-image {
    width: 80px;
    height: 80px;
    border-radius: 8px;
    margin-right: 15px;
}

.product-info .product-details {
    flex: 1;
}

.product-info .product-details h4 {
    font-size: 16px;
    margin: 5px 0;
    line-height: 1.4;
}

.product-info .product-details .price {
    color: #ff5000;
    font-size: 18px;
    font-weight: bold;
}

.quantity-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.address-section {
    background-color: #f9f9f9;
    padding: 15px;
    border-radius: 8px;
    margin-bottom: 20px;
    cursor: pointer;
}

.address-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
}

.address-header .title {
    font-weight: bold;
}

.address-content {
    font-size: 14px;
}

.address-info {
    display: flex;
    align-items: center;
    margin-bottom: 5px;
}

.address-info .receiver {
    margin-right: 10px;
    font-weight: bold;
}

.address-info .phone {
    margin-right: 10px;
}

.address-detail {
    color: #666;
    line-height: 1.5;
}

.address-empty {
    text-align: center;
    padding: 10px 0;
}

.payment-header {
    font-weight: bold;
    margin-bottom: 15px;
}

.payment-methods {
    display: flex;
}

.payment-method {
    display: flex;
    align-items: center;
    padding: 10px 15px;
    border: 1px solid #eee;
    border-radius: 8px;
    margin-right: 10px;
    cursor: pointer;
}

.payment-method.active {
    border-color: #ff5000;
    background-color: #fff5f5;
}

.method-icon {
    width: 24px;
    height: 24px;
    margin-right: 8px;
}

.method-icon img {
    width: 100%;
    height: 100%;
    object-fit: contain;
}

.method-name {
    font-size: 14px;
}

.payment-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.payment-amount {
    font-size: 16px;
}

.payment-amount .amount {
    color: #ff5000;
    font-weight: bold;
    font-size: 18px;
}

/* 地址选择抽屉样式 */
.address-list-container {
    padding: 15px;
}

.address-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px;
    margin-bottom: 10px;
    border: 1px solid #eee;
    border-radius: 8px;
    cursor: pointer;
}

.address-item.active {
    border-color: #ff5000;
    background-color: #fff5f5;
}

.check-icon {
    color: #ff5000;
    font-size: 20px;
}

.address-actions {
    margin-top: 20px;
    text-align: center;
}

/* 支付二维码弹窗样式 */
.qr-code-container {
    text-align: center;
}

.qr-code-canvas {
    width: 200px;
    height: 200px;
    margin: 0 auto 15px;
    display: block;
}

.qr-code-info {
    margin-bottom: 15px;
    font-size: 14px;
}

.qr-code-info p {
    margin: 5px 0;
}

.sandbox-tip {
    color: #ff5000;
    font-size: 12px;
}

.payment-instruction {
    color: #999;
    font-size: 12px;
    margin-top: 15px;
}
</style>